/**
 * storage 操作
 * @example
 * // localStorage
 * storage.set('key', value)
 * storage.get('key')
 *
 * // sessionStorage
 * storage.session.set('key', value)
 * storage.session.get('key')
 */
const storage = {
  storage: localStorage,
  session: {
    storage: sessionStorage,
  },
}
const api = {
  set(key, value) {
    this.storage.setItem(getStorageKey(key), toggleSerialize(value, 'serialize'))
  },
  get(key) {
    return toggleSerialize(this.storage.getItem(getStorageKey(key)), 'deserialize')
  },
  has(key) {
    return !!this.get(key)
  },
  remove(key) {
    this.storage.removeItem(getStorageKey(key))
  },
  clear() {
    Array.from({ length: this.storage.length }, (v, index) => this.storage.key(index))
      .filter((i) => i.startsWith(prefix))
      .forEach((i) => this.remove(i.replace(prefix, '')))
  },
}

Object.assign(storage, api)
Object.assign(storage.session, api)

const prefix = 'pinf-finacial-tools:'
const getStorageKey = (key) => (key.startsWith(prefix) ? key : `${prefix}${key}`)
const toggleSerialize = (val, type = 'serialize') => {
  try {
    return type === 'serialize' ? JSON.stringify(val) : JSON.parse(val)
  } catch (e) {
    console.error(e)
    return val || undefined
  }
}

export default storage
